package api

import (
	"aiworkc/internal/domain"
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"path/filepath"

	"aiworkc/internal/logic"
	"aiworkc/internal/svc"
	"aiworkc/pkg/httpx"
	"github.com/segmentio/ksuid"
)

type Upload struct {
	svcCtx *svc.ServiceContext
	chat   logic.Chat
}

func NewUpload(svcCtx *svc.ServiceContext, chat logic.Chat) *Upload {
	return &Upload{
		svcCtx: svcCtx,
		chat:   chat,
	}
}

func (h *Upload) InitRegister(engine *gin.Engine) {
	g := engine.Group("v1/upload", h.svcCtx.Jwt.Handler)
	g.POST("/file", h.File)
	g.POST("/multiplefiles", h.Multiplefiles)
}

func (h *Upload) File(ctx *gin.Context) {
	file, header, err := ctx.Request.FormFile("file")
	var (
		filename string
		buf      = bytes.NewBuffer(nil)
	)
	defer file.Close()

	if _, err := io.Copy(buf, file); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	filename = ksuid.New().String() + filepath.Ext(header.Filename)

	newFile, err := os.Create(h.svcCtx.Config.Upload.SavePath + filename)
	if err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}
	defer newFile.Close()

	if _, err := newFile.Write(buf.Bytes()); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	resp := domain.FileResp{
		Host:     h.svcCtx.Config.Host,
		File:     fmt.Sprintf("%s%s", h.svcCtx.Config.Upload.SavePath, filename),
		Filename: filename,
	}

	chat := ctx.Request.FormValue("chat")
	if len(chat) > 0 {
		h.chat.File(ctx.Request.Context(), []*domain.FileResp{
			&resp,
		})
	}

	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, resp)
	}
}

func (h *Upload) Multiplefiles(ctx *gin.Context) {
}
